package GameObject;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;

public class TilledMap extends ImageObject {

	private int nRow;
	private int nCol;
	private int[][] terrainMatrix;
	private int mapCol;
	private int mapRow;

	public TilledMap(BufferedImage res, int col, int row, int[][] matrix) {
		init(res, col, row, matrix);
	}

	public int getMapCol() {
		return mapCol;
	}

	public int getMapRow() {
		return mapRow;
	}

	private void init(BufferedImage res, int col, int row, int[][] matrix) {
		bufferImg = res;

		nRow = row;
		nCol = col;
		width = bufferImg.getWidth() / col;
		height = bufferImg.getHeight() / row;
		terrainMatrix = matrix;
		mapCol = matrix.length;
		mapRow = matrix[0].length;
		innerPoint = new Point(0, 0);
		position = new Point(0, 0);
		scaleX = 1f;
		scaleY = 1f;
	}

	public int getMatrix(int i, int j) {
		return terrainMatrix[i][j];
	}
	
	public int getCellWidth() {
		return width ;
	}
	public int getCellHeight() {
		return height ;
	}
	@Override
	public int getWidth() {
		return width * mapCol;
	}

	@Override
	public int getHeight() {
		return height * mapRow;
	}

	@Override
	public void draw(Graphics2D g, int dx, int dy) {
		Point p = transform(g, dx, dy);
		int x = p.x;
		int y = p.y;

		for (int i = 0; i < mapCol; i++) {
			for (int j = 0; j < mapRow; j++) {
				int f = terrainMatrix[i][j];
				int r = f / nCol;
				int c = f % nCol;
				int w = (int) (width * scaleX);
				int h = (int) (height * scaleX);
				int x0 = (int) (x - innerPoint.x * scaleX);
				int y0 = (int) (y - innerPoint.y * scaleX);
				g.drawImage(bufferImg,
						x0 + w * j, y0 + h * i,
						x0 + w * (j + 1), y0 + h * (i + 1),
						c * width, r * height,
						(c + 1) * width, (r + 1) * height,
						null);
			}
		}
	}
}
